<template>
  <div>
    <div>
      <el-card style="margin: 10px" class="box-card">
        <div class="body">
          <!-- 头部搜索区域 -->
          <el-form label-width="85px" ref="searchRef" :model="data">
            <el-row>
              <el-col :span="6">
                <el-form-item prop="tags" label="标签名称">
                  <el-input
                    style="width: 100%"
                    v-model="data.tags"
                    size="small"
                    placeholder="请输入"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="province" label="城市">
                  <el-select
                    style="width: 100%"
                    placeholder="请选择"
                    v-model="data.province"
                    size="small"
                    @change="choseProvince"
                  >
                    <el-option
                      v-for="item in provinces"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="city" label="地区">
                  <el-select
                    style="width: 100%"
                    v-model="data.city"
                    placeholder="请选择"
                    size="small"
                    autocomplete="on"
                    @change="choseCity"
                  >
                    <el-option
                      v-for="item in cities"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="shortName" label="企业简称">
                  <el-input
                    style="width: 100%"
                    v-model="data.shortName"
                    size="small"
                  ></el-input> </el-form-item
              ></el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item prop="state" label="状态">
                  <el-select
                    v-model="data.state"
                    placeholder="请选择"
                    style="width: 100%"
                    size="small"
                  >
                    <el-option
                      v-for="item in states"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select> </el-form-item
              ></el-col>

              <el-col :span="6">
                <el-row type="flex" justify="end">
                  <el-button @click="resetField" size="small">清除</el-button>
                  <el-button
                    type="primary"
                    class="search"
                    @click="search"
                    size="small"
                    >搜索</el-button
                  >
                </el-row>
              </el-col>
              <el-col :span="12" style="text-align: right"
                ><el-button type="success">
                  <i class="el-icon-edit" @click="add">新增用户</i></el-button
                ></el-col
              >
            </el-row>
          </el-form>
          <!-- 多少条记录 -->
          <!-- 数量提示条 -->
          <el-row style="width: 100%">
            <el-col :span="24">
              <div class="grid-content bg-purple-dark">
                <i class="el-icon-info"></i>
                <span class="totalSpan">数据一共 {{ counts }} 条</span>
              </div></el-col
            >
          </el-row>
          <!-- 主体 -->
          <el-table :data="list" style="width: 100%">
            <el-table-column
              align="center"
              prop="id"
              label="序号"
              width="181"
            />
            <el-table-column
              align="center"
              prop="number"
              label="企业编号"
              width="127"
            />
            <el-table-column align="center" prop="shortName" label="企业简称" />
            <el-table-column align="left" prop="tags" label="标签" />
            <el-table-column align="center" prop="creatorID" label="创建者" />
            <el-table-column align="center" prop="addDate" label="创建日期" />
            <el-table-column align="center" prop="remarks" label="备注" />
            <el-table-column align="center" prop="state" label="状态">
              <template v-slot="{ row }">
                <span>{{ row.state === 1 ? "已启用" : "已禁用" }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="180">
              <template #default="{ row }">
                <el-button type="primary" plain circle @click="edit(row)">
                  <i class="el-icon-edit"></i
                ></el-button>
                <el-button
                  type="warning"
                  v-if="row.state === 1"
                  plain
                  circle
                  @click="forbidden(row)"
                >
                  <i class="el-icon-close"></i
                ></el-button>
                <el-button
                  type="success"
                  v-if="row.state === 0"
                  plain
                  circle
                  @click="forbidden(row)"
                >
                  <i class="el-icon-check"></i
                ></el-button>
                <el-button type="danger" plain circle @click="del(row)">
                  <i class="el-icon-delete"></i
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <paging
            :counts="counts"
            :data="data"
            :n="[10, 20, 30, 50]"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"
          ></paging>
        </div>
      </el-card>
    </div>
    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="showDialog" @close="btncancle">
      <el-form ref="addRef" :model="addFormdata" :rules="rules">
        <el-form-item label-width="120px" label="企业名称" prop="shortName"
          ><el-input v-model="addFormdata.shortName"></el-input>
        </el-form-item>
        <el-form-item label-width="120px" label="所属公司" prop="company"
          ><el-input v-model="addFormdata.company"></el-input>
        </el-form-item>
        <el-form-item label-width="120px">
          <p>https://www.tianyancha.com (在此可查询所属公司全称及简称)</p>
        </el-form-item>

        <el-form-item label-width="120px" label="城市地区" prop="city">
          <el-select
            v-model="addFormdata.province"
            placeholder="请选择"
            @change="choseProvince"
          >
            <el-option
              v-for="item in provinces"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="addFormdata.city"
            placeholder="请选择"
            autocomplete="on"
            @change="choseCity"
          >
            <el-option
              v-for="item in cities"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label-width="120px" label="方向(企业标签)" prop="tags"
          ><el-input v-model="addFormdata.tags"></el-input>
        </el-form-item>

        <el-form-item label-width="120px" label="备注" prop="remarks"
          ><el-input
            v-model="addFormdata.remarks"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="btncancle">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>
    <!-- <mouserA></mouserA> -->
  </div>
</template>

<script>
// 接口
import { list, add, detail, update, remove } from "../../api/hmmm/companys";
// 分页
import paging from "../../components/Paging";
// 时间
import moment from "moment";
// 地区
import ChineseDistricts from "@/api/hmmm/area";
export default {
  data() {
    return {
      ChineseDistricts: ChineseDistricts,
      data: {
        page: 1,
        pagesize: 10,
        tags: null,
        province: null,
        city: null,
        shortName: null,
        state: null,
      },
      provinces: [],
      cities: [],
      shi1: [],
      states: [
        { id: 1, label: "启用" },
        { id: 0, label: "禁用" },
      ],
      list: [],
      currentPage: 1,
      counts: 1,
      showDialog: false,
      title: "创建用户",
      addFormdata: {
        city: "",
        company: "",
        isFamous: true,
        province: "",
        remarks: "",
        shortName: "",
        tags: "",
      },
      rules: {
        shortName: [
          { required: true, massage: "请输入公司简称", triggers: "blur" },
        ],
        company: [
          { required: true, massage: "请输入所属公司", triggers: "blur" },
        ],
        city: [{ required: true, massage: "请输入城市地区", triggers: "blur" }],
        tags: [{ required: true, massage: "请输入标签", triggers: "blur" }],
        remarks: [{ required: true, massage: "请输入备注", triggers: "blur" }],
      },
      comArr: [],
    };
  },
  components: { paging },
  created() {
    this.getCompanyList();
    this.getCityData();
  },
  methods: {
    // 获取企业数据
    async getCompanyList() {
      try {
        const { data } = await list(this.data);
        data.items.forEach((item) => {
          item.addDate = moment(item.addDate).format("YYYY-MM-DD");
        });
        if (JSON.parse(localStorage.getItem("comArr"))) {
          data.items.forEach((item) => {
            JSON.parse(localStorage.getItem("comArr")).forEach((item2) => {
              item.id === item2.id ? (item.state = item2.state) : "";
            });
          });
        }
        this.list = data.items;
        this.counts = data.counts;
        this.data.page = data.page;
        this.data.pagesize = data.pagesize;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取全国拿城市
    getCityData() {
      this.ChineseDistricts.forEach((item) => {
        // console.log(item)
        item.cityList?.forEach((item2) => {
          this.provinces.push({
            id: item2.code,
            label: item2.name,
            children: item2.areaList,
          });
        });
      });
    },
    // 选省
    choseProvince(e) {
      this.cities = [];
      this.provinces.forEach((item) => {
        if (item.id === e) {
          // console.log(item)
          this.addFormdata.province = item.label;
          this.data.province = item.label;
          this.shi1 = item.children;
          this.data.city = item.children[0].name;
          this.addFormdata.city = item.children[0].name;
          this.shi1.forEach((citem) => {
            this.cities.push({
              id: citem.code,
              label: citem.name,
            });
          });
        }
      });
    },
    // 选市
    choseCity(e) {
      this.cities.forEach((item) => {
        // console.log(item)
        if (item.id === e) {
          this.addFormdata.city = item.label;
          this.data.city = item.label;
        }
      });
    },
    // 每页显示条数传值
    handleSizeChange(val) {
      this.data.pagesize = val;
      this.getCompanyList();
    },
    handleCurrentChange(val) {
      this.data.page = val;
      this.getCompanyList();
    },
    resetField() {
      this.$refs.searchRef.resetFields();
    },
    search() {
      this.getCompanyList();
    },
    // 新增按钮
    async add() {
      this.resetField();
      this.addFormdata.province = "";
      this.data.province = "";
      this.addFormdata.city = "";
      this.title = "创建用户";
      this.showDialog = true;
    },
    // 弹窗确定
    async save() {
      if (this.title === "创建用户") {
        try {
          await this.$refs.addRef.validate();
          await add(this.addFormdata);
          this.$message.success("创建成功");
          this.data.province = "";
          this.resetField();
          this.getCompanyList();
        } catch (error) {
          console.log(error);
        }
      } else if (this.title === "编辑用户") {
        try {
          await this.$refs.addRef.validate();
          await update(this.addFormdata);
          this.$message.success("编辑成功");
          this.data.province = "";
          this.resetField();
          this.getCompanyList();
        } catch (error) {
          console.log(error);
        }
      }
      this.showDialog = false;
    },
    btncancle() {
      this.showDialog = false;
      this.$refs.addRef.resetFields();
    },
    // 编辑
    async edit(row) {
      console.log(this.list);
      console.log(row);
      this.title = "编辑用户";
      this.showDialog = true;
      const { data } = await detail(row);
      this.provinces.forEach((item) => {
        if (item.label === data.province) {
          const e = item.id;
          this.choseProvince(e);
        }
      });
      if (data.isFamous === 1) data.isFamous = true;
      this.addFormdata = { ...data };
    },
    // 删除
    async del(row) {
      this.$confirm("该项操作不可恢复！确定删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await remove(row);
          this.$message.success("删除成功");
          this.getCompanyList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消删除",
          });
        });
    },
    // 禁用
    forbidden(row) {
      this.$confirm(row.state === 1 ? "确定要禁用吗" : "确定要启用吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          row.state = row.state === 0 ? 1 : 0;
          this.$message.success(row.state === 0 ? "禁用成功" : "启用成功");
          this.list.forEach((item) => {
            this.comArr.push({ id: item.id, state: item.state });
          });
          localStorage.setItem("comArr", JSON.stringify(this.comArr));
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消成功",
          });
        });
    },
  },
};
</script>

<style scoped >
.box-card {
  background-color: rgba(255, 255, 255, 0.5);
}
.grid-content {
  border-radius: 4px;
  min-height: 26px;
}
.bg-purple-dark {
  margin: 10px 0;
  padding: 5px 15px;
  color: #909399;
  background: #f4f4f5;
}
.totalSpan {
  font-size: 12px;
  margin-left: 10px;
}
</style>
